package com.hxzy.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 生成验证码类说明
 *
 * @author admin
 * @date 2021-09-01
 */
@Controller
public class CaptchaController {

    @GetMapping ("/captcha/gif")
    public void gifCaptcha(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "width",required = false,defaultValue= "150") int width,
                           @RequestParam(value = "height",required = false,defaultValue= "50") int height,
                           @RequestParam(value = "len",required = false,defaultValue= "4") int len) throws Exception {

        // 使用gif验证码
        GifCaptcha gifCaptcha = new GifCaptcha(width,height,len);
        CaptchaUtil.out(gifCaptcha, request, response);

        //存储到session中，供下次验证时候使用
        HttpSession session=request.getSession();
        session.setAttribute("captchaValue", gifCaptcha.text().toLowerCase());

    }

    @GetMapping ("/captcha/png")
    public void pngCaptcha(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "width",required = false,defaultValue= "150") int width,
                           @RequestParam(value = "height",required = false,defaultValue= "50") int height,
                           @RequestParam(value = "len",required = false,defaultValue= "4") int len) throws Exception {

        SpecCaptcha captcha = new SpecCaptcha(width, height);
        captcha.setLen(len);
        CaptchaUtil.out(captcha, request, response);

        //存储到session中，供下次验证时候使用
        HttpSession session=request.getSession();
        session.setAttribute("captchaValue", captcha.text().toLowerCase());
    }

    @GetMapping ("/captcha/arith")
    public void arithmeticCaptcha(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "width",required = false,defaultValue= "150") int width,
                           @RequestParam(value = "height",required = false,defaultValue= "50") int height,
                           @RequestParam(value = "len",required = false,defaultValue= "2") int len) throws Exception {

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(width, height);
        captcha.setLen(len);
        CaptchaUtil.out(captcha, request, response);

        //存储到session中，供下次验证时候使用
        HttpSession session=request.getSession();
        session.setAttribute("captchaValue", captcha.text().toLowerCase());
    }

}
